package pattern4.promise.demo2SelfImpl;

import utils.PrintUtil;

/**
 * 任务：执行需要4s, 把字符串全部转成小写
 *
 * @创建人 liweijia
 * @创建时间 2022/7/24
 * @描述 程序的主要用途
 */
public class MyTask extends Thread {

    /**
     * 锁
     */
    private final Object lock;

    /**
     * 输入
     */
    private final String input;

    /**
     * 输出
     */
    private volatile String output;

    /**
     * 完成
     */
    private volatile boolean isDone;

    public MyTask(String input) {
        this.input = input;
        this.lock = new Object();
        this.output = null;
        this.isDone = false;
    }

    @Override
    public void run() {
        synchronized (lock) {
            PrintUtil.print("字符串：" + this.input + "开始转换");
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            this.output = this.input.toLowerCase();
            this.isDone = true;
            this.lock.notifyAll();
            PrintUtil.print("转换完毕");
        }
    }

    public boolean isDone() {
        return isDone;
    }

    public String get() {
        synchronized (lock) {
            while (!isDone) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            return this.output;
        }
    }
}
